package vg.services.config_manager;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;



/**
 * This class contains options for system. This is singleton.
 * @author tzolotuhin
 */
public class ConfigManager implements IConfigManager {
	private static ConfigManager instance = null;
	private Properties prop;
	private final static String DEF_FILE_NAME = "data/config.ini";
	//-------------------------------------------------------------------------
	private ConfigManager() {
		FileInputStream in = null;
		try {
			in = new FileInputStream(DEF_FILE_NAME);
			this.prop = new Properties();
			this.prop.load(in);
		} catch (IOException ex) {
			this.prop = new Properties();
			System.err.println("Couldn't open file " + DEF_FILE_NAME + ".");
			System.err.println("Try create new config file.");
			File f = new File(DEF_FILE_NAME);
			try {
				if(f.createNewFile()) {
					System.err.println("Creating of config file. Successfully");
				} else {
					System.err.println("Creating of config file. Fail.");
				}
			} catch (IOException e) {
				System.err.println("Creating of config file. Fail.");				
			}
		} finally {
			if(in != null) {
				try {
					in.close();
				} catch (IOException ex) {}
			}
		}
		
		//finalize of services
		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				save();
			}
		});	
	}
	/**
	 * This method returns instance.
	 * Note : in the beginning you must invoke method load. 
	 * @return current configuration.
	 */
	public synchronized static ConfigManager getInstance() {
		if(instance==null) {
			instance = new ConfigManager();
		}
		return(instance);
	}
	public synchronized String getProperty(final String key) {
        String value = null;
        
        if (this.prop.containsKey(key))
            value = (String)this.prop.get(key);
        return(value);
    }
	public synchronized void setProperty(String key, String value) {
		if (value == null)
			this.prop.remove(key);
		else
			this.prop.setProperty(key, value);
	}
	public void save() {
		OutputStream out = null;
		try {
			out = new FileOutputStream(DEF_FILE_NAME);
			this.prop.store(out, "");
		} catch(Throwable ex) {
			System.err.println(ex.getMessage());
		} finally {
			if(out != null) {
				try {
					out.close();
				} catch(IOException ex) {}
			}
		}
	}

}
